import WXRealLogUtil from "../../../StartAb/WXRealLogUtil";
import ActionHelper from "../../TFrame/script/helper/ActionHelper";
import CocosHelper from "../../TFrame/script/helper/CocosHelper";
import EventCenter from "../../TFrame/script/helper/EventCenter";
import EventNames from "../EventNames";
import LevelLogic from "../logic/LevelLogic";
import PlayerDataMgr from "../PlayerDataMgr";
import ResManager from "../ResManager";
import GameLogicController from "./GameLogicController";
import StatusProperties from "./StatusProperties";

const { ccclass, property } = cc._decorator;

@ccclass
export default class GameViewController extends cc.Component {

    @property(cc.Node)
    viewScaleNode1: cc.Node = null;

    @property(cc.Node)
    viewScaleNode2: cc.Node = null;

    @property({ type: cc.SpriteFrame, displayName: "找到的图片" })
    spotRightSpriteFrame: cc.SpriteFrame = null

    @property({ type: cc.Node })
    hintParNode1: cc.Node = null;

    @property({ type: cc.Node })
    hintParNode2: cc.Node = null;

    @property({ type: cc.SpriteFrame })
    flyPicture: cc.SpriteFrame = null;

    @property({ type: cc.SpriteFrame })
    errorPicture: cc.SpriteFrame = null;

    @property({ type: cc.Node, displayName: "玫瑰飞达目标父节点" })
    flyTargetRoot: cc.Node = null;

    @property(cc.Prefab)
    levelEndNodePrefab: cc.Prefab = null;

    @property(cc.AudioClip)
    errorAudio: cc.AudioClip = null;

    @property({ type: [cc.AudioClip] })
    foundAudios: cc.AudioClip[] = [];

    @property(cc.AudioClip)
    finishAudio: cc.AudioClip = null;

    @property(cc.AudioClip)
    tipAudio: cc.AudioClip = null;

    @property(cc.Node)
    buttonUI: cc.Node = null;

    scaleTween1: cc.Tween = null;
    scaleTween2: cc.Tween = null;

    protected onLoad(): void {
        GameLogicController.getInstance().reset();
        this.buttonUI.active = false;
        if (LevelLogic.getCurrentPlayLevel() == 0 && PlayerDataMgr.getInstance().turotial_played == 0) {
            EventCenter.once(EventNames.DiffShowDone, () => {
                cc.assetManager.getBundle("GameAb").load("prefab/TutorialRoot", cc.Prefab, (err: Error, pf: cc.Prefab) => {
                    if (err)
                        return console.log(err.message);
                    if (this.isValid) {
                        let dialog = cc.instantiate(pf);
                        dialog.parent = cc.Canvas.instance.node;
                        this.buttonUI.active = true;
                    }
                });
            }, this)
        } else {
            this.buttonUI.active = true;
        }
        EventCenter.on(EventNames.ScaleChange, this.diffAreaScale, this);

        EventCenter.on(EventNames.SpotDiffRight, this.spotDiffRight, this)

        EventCenter.on(EventNames.ReqShowHint, this.reqShowHint, this);

        EventCenter.on(EventNames.SpotDiffError, this.spotDiffError, this);

        EventCenter.once(EventNames.DiffAllFound, () => {
            this.diffAreaScale(1.0);
            this.scheduleOnce(this.showLevelEnd, 1.5)
        }, this);

        if (PlayerDataMgr.getInstance().autoPlay == true) {
            for (let i = 0; i < 5; ++i) {
                this.scheduleOnce(() => {
                    GameLogicController.getInstance().findDifference(i);
                }, 0.5)
            }
        }

        WXRealLogUtil.info(`开始第${ResManager.currentLevelIndex + 1}关`)
    }

    diffAreaScale(scale: number) {
        this.scaleTween1 && this.scaleTween1.stop();
        this.scaleTween2 && this.scaleTween2.stop();
        this.scaleTween1 = cc.tween(this.viewScaleNode1).to(0.15, { scale: scale, x: 0, y: 0 });
        this.scaleTween2 = cc.tween(this.viewScaleNode2).to(0.15, { scale: scale, x: 0, y: 0 });
        this.scaleTween1.start();
        this.scaleTween2.start();
    }

    spotDiffRight(ptLocal: cc.Vec2, hitGameArea) {
        let node1 = CocosHelper.createSpriteNode(this.spotRightSpriteFrame);
        node1.parent = this.viewScaleNode1
        node1.setPosition(ptLocal);
        let size = ResManager.getDiffConfigRect(hitGameArea).size
        node1.setContentSize(cc.size(size.width + 20, size.height + 20))

        let node2 = CocosHelper.createSpriteNode(this.spotRightSpriteFrame);
        node2.parent = this.viewScaleNode2
        node2.setPosition(ptLocal);
        node2.setContentSize(node1.getContentSize())

        this.hideHint();

        this.flyFoundFlag(ptLocal, hitGameArea);

        let audio = this.foundAudios[GameLogicController.getInstance().foundCount - 1]
        audio && cc.audioEngine.playEffect(audio, false);
    }

    spotDiffError(ptWorld: cc.Vec2, hitGameArea) {
        let localParent = hitGameArea == 1 ? this.viewScaleNode1 : this.viewScaleNode2;
        let node = CocosHelper.createSpriteNode(this.errorPicture);
        node.parent = localParent
        node.setPosition(node.parent.convertToNodeSpaceAR(ptWorld));
        cc.tween(node).to(0.5, {
            scale: 0.5,
            opacity: 0
        }).call(() => {
            node.destroy()
        }).start();

        this.errorAudio && cc.audioEngine.playEffect(this.errorAudio, false)
    }

    reqShowHint(ptLocal: cc.Vec2) {
        this.hintParNode1.active = true;
        this.hintParNode1.position = cc.v3(ptLocal);
        this.hintParNode2.active = true;
        this.hintParNode2.position = cc.v3(ptLocal);
        StatusProperties.hintAliving = true;
        this.tipAudio && cc.audioEngine.playEffect(this.tipAudio, false);
    }

    hideHint() {
        this.hintParNode1.getComponent(cc.ParticleSystem).resetSystem();
        this.hintParNode2.getComponent(cc.ParticleSystem).resetSystem();
        this.hintParNode1.active = false;
        this.hintParNode2.active = false;
        StatusProperties.hintAliving = false;
    }

    flyFoundFlag(ptLocal: cc.Vec2, hitGameArea) {
        let localParent = hitGameArea == 1 ? this.viewScaleNode1 : this.viewScaleNode2;
        let startPtWorld = localParent.convertToWorldSpaceAR(ptLocal);
        let flyNode = CocosHelper.createSpriteNode(this.flyPicture);
        flyNode.parent = cc.Canvas.instance.node;
        let startPtLocal = flyNode.parent.convertToNodeSpaceAR(startPtWorld);
        flyNode.position = cc.v3(startPtLocal);

        let endNode = this.flyTargetRoot.getChildByName("" + GameLogicController.getInstance().foundCount);
        if (endNode) {
            let targetPtWorld = endNode.convertToWorldSpaceAR(cc.Vec2.ZERO);
            let targetPtLocal = flyNode.parent.convertToNodeSpaceAR(targetPtWorld);
            let action = ActionHelper.getBezierAction(0.75, startPtLocal, targetPtLocal);
            flyNode.runAction(action);
        }
    }

    showLevelEnd() {
        let node = cc.instantiate(this.levelEndNodePrefab);
        node.parent = cc.Canvas.instance.node;
        this.finishAudio && cc.audioEngine.playEffect(this.finishAudio, false)
    }
}
